//二叉搜索树
//右节点比根节点大，左节点比根节点小
public class BinarySearchTree {
    class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }

    }
    public TreeNode root;

    //最好情况(插入和搜索),如果这棵树是单分支的那就是O(N)
    //AVL 红黑树基本上就是高度平衡的，可以达到O(logn)
    //时间复杂度:O(logn)
    //空间复杂度:O(n)

    //搜索
    public boolean search(int val){
        TreeNode cur=root;
        while(cur!=null){
            if(cur.val>val){
                cur=cur.left;
            }else if(cur.val<val){
                cur=cur.right;
            }else{
                return true;
            }
        }
        return false;
    }

    //插入
    public void insert(int val){
        TreeNode newNode = new TreeNode(val);
        if(root==null){
            root=newNode;
            return ;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.val>val){
                parent=cur;
                cur=cur.left;
            }else if(cur.val<val){
                parent=cur;
                cur=cur.right;
            }else {
                return;
            }
        }
        if(parent.val>val){
            parent.left=newNode;
        }
        if(parent.val<val){
            parent.right=newNode;
        }
    }
    public void remove(int val){
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.val>val){
                parent=cur;
                cur=cur.left;
            }else if(cur.val<val){
                parent=cur;
                cur=cur.right;
            }else {
                removeNode(cur,parent);
                return;
            }
        }
    }


    //删除
    private void removeNode(TreeNode cur, TreeNode parent) {
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }if(parent.left==cur){
                parent.left=cur.right;
            }else{
                parent.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }if(parent.left==cur){
                parent.left=cur.left;
            }else{
                parent.right=cur.left;
            }
        }else{
            //可左可右
            //如果是左的话要找左子树的最右边的最大值
            //如果是右的话要找右子树的最左边的最小值

            //这里我们选择找右子树
            TreeNode target=cur.right;
            TreeNode parentTarget=cur;
            while(target.left!=null){
                parentTarget=target;
                target=target.left;
            }
            cur.val=target.val;
            if(parentTarget.left==target){
                //这里不用判断target的右边是否为空了，直接让他等于target.right，如果为空那就直接为空了,下面else同理
                parentTarget.left=target.right;
            }else{
                parentTarget.right=target.right;
            }
        }
    }

}
